package cn.tqfeiyang.smartadmin.commons.application;

import cn.tqfeiyang.smartadmin.commons.toolbox.NetworkUtils;
import cn.tqfeiyang.smartadmin.commons.toolbox.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Web服务器就绪监听器
 *
 * @author tqfeiyang
 * @since 2024/8/21 17:29
 */
@Slf4j
@Component
@Order(value = 1024)
public class WebServerListener implements ApplicationListener<WebServerInitializedEvent>  {

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        showProjectMessage(event);
    }

    /**
     * 显示项目信息
     */
    private void showProjectMessage(WebServerInitializedEvent event) {
        WebServerApplicationContext context = event.getApplicationContext();
        Environment env = context.getEnvironment();

        String ip = NetworkUtils.getLocalhostIp();
        Integer port = event.getWebServer().getPort();
        String contextPath = env.getProperty("server.servlet.context-path");
        if (contextPath == null || "/".equals(contextPath)) {
            contextPath = "";
        }

        String profile = StringUtils.collectionToCommaDelimitedString(Arrays.asList(env.getActiveProfiles()));//env.getProperty("spring.profiles.active");
        String projectName = env.getProperty("spring.application.name");

        String title = String.format("\n----------------【%s】 服务已成功启动 -------------------", projectName);
        String localhostUrl = String.format("http://localhost:%d%s", port, contextPath);
        String externalUrl = String.format("http://%s:%d%s", ip, port, contextPath);
        String swaggerUrl = String.format("http://%s:%d%s/swagger-ui/index.html", ip, port, contextPath);
        String knife4jUrl = String.format("http://%s:%d%s/doc.html", ip, port, contextPath);
        log.warn("\n{}\n" +
                        "\t当前启动环境:\t{}" +
                        "\n\t服务本机地址:\t{}" +
                        "\n\t服务外网地址:\t{}" +
                        "\n\tSwagger地址:\t{}" +
                        "\n\tknife4j地址:\t{}" +
                        "\n--------------------------------------------------------------------------\n",
                title, profile, localhostUrl, externalUrl, swaggerUrl, knife4jUrl);
    }
}
